var mongoose = require('mongoose');
// mongoose.set('useCreateIndex', true); // Mongoose解决MongoDB弃用警告

/**
 * @UserSchema
 * 设置表数据类型
 */
var UserSchema = new mongoose.Schema({
    username: { type: String, required: true, index: { unique: true } },
    password: { type: String, required: true },
    email: { type: String, required: true, index: { unique: true } },
    data: { type: Date, default: Date.now() }

});

var UserModel = mongoose.model('user', UserSchema);
UserModel.createIndexes();
/**
 * @save
 * 表储存方法，当表成功储存返回true，否则返回false
 */
var save = (data) => {
    var user = new UserModel(data);
    return user.save()
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
}

var findLogin = (data) => {
    return UserModel.findOne(data);
}

var updataPassword = (email, password) => {
    return UserModel.updateOne({ email }, { $set: { password } })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        })
}

module.exports = {
    save,
    findLogin,
    updataPassword
}